package com.tianqingwl.gsystem.resources.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianqingwl.gsystem.common.exception.IllegalRequestParamException;
import com.tianqingwl.gsystem.common.util.StringUtil;
import com.tianqingwl.gsystem.resources.mapper.SysPermissionMapper;
import com.tianqingwl.gsystem.resources.pojo.SysPermission;
import com.tianqingwl.gsystem.resources.service.SysPermissionService;
import com.tianqingwl.gsystem.resources.vo.MenuInfoVo;
import com.tianqingwl.gsystem.resources.vo.PermissionVo;
import com.tianqingwl.gsystem.sysuser.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<SysPermission> findUserRolePermissionByUsername(String username) {
        return sysPermissionMapper.findUserRolePermissionByUsername(username);
    }

    @Override
    public List<MenuInfoVo> getUserMenuInfoVo(String username) {
        List<SysPermission> userPermissions = findUserRolePermissionByUsername(username);

        //将bean转为vo存入集合
        Map<Long, MenuInfoVo> menuInfoVoMap = new HashMap<>();
        List<MenuInfoVo> menuInfoVoList = new ArrayList<>();
        List<MenuInfoVo> resultList = new ArrayList<>();

        for (SysPermission userPermission : userPermissions) {
            MenuInfoVo menuInfoVo = new MenuInfoVo();
            menuInfoVo.setId(userPermission.getPerId());
            menuInfoVo.setParentId(userPermission.getParentId());
            menuInfoVo.setTitle(userPermission.getPerName());
            menuInfoVo.setIcon(userPermission.getIcon());

            switch (userPermission.getTargetType()){
                case 1:
                    menuInfoVo.setTarget("_self");
                    break;
                case 2:
                    menuInfoVo.setTarget("_blank");
                    break;
                case 3:
                    menuInfoVo.setTarget("_newtab");
                    break;
            }

            menuInfoVo.setHref(userPermission.getUrl());
            menuInfoVoMap.put(userPermission.getPerId(), menuInfoVo);
            menuInfoVoList.add(menuInfoVo);
        }

        MenuInfoVo rootMenu = new MenuInfoVo();
        rootMenu.setTitle("主页");
        resultList.add(rootMenu);
        //组合
        for (MenuInfoVo menuInfoVo : menuInfoVoList) {
            if (menuInfoVo.getParentId() == null || menuInfoVo.getParentId() == -1) {
                rootMenu.getChild().add(menuInfoVo);
            } else {
                //获取父节点
                MenuInfoVo menuInfoP = menuInfoVoMap.get(menuInfoVo.getParentId());
                if (menuInfoP != null) {
                    menuInfoP.getChild().add(menuInfoVo);
                }
            }
        }
        return resultList;
    }

    @Override
    public List<PermissionVo> listPermissionVo(Long roleId,Boolean roleIn) {

        List<SysPermission> sysPermissions = sysPermissionMapper.selectPermissionList(roleId,roleIn);
        List<PermissionVo> permissionVoList = new ArrayList<>();
        for (int i = 0; i < sysPermissions.size(); i++) {
            SysPermission sysPermission = sysPermissions.get(i);
            PermissionVo permissionVo = new PermissionVo();
            permissionVo.setAuthorityId(sysPermission.getPerId());
            permissionVo.setAuthority(sysPermission.getPerFlag());
            permissionVo.setAuthorityName(sysPermission.getPerName());
            permissionVo.setMenuIcon(sysPermission.getIcon());
            permissionVo.setOrderNumber((i + 1));
            permissionVo.setParentId(sysPermission.getParentId());
            permissionVo.setMenuUrl(sysPermission.getUrl());
            permissionVo.setType(sysPermission.getResType());
            permissionVo.setAuthorityDesc(sysPermission.getPerDesc());
            permissionVoList.add(permissionVo);
        }

        return permissionVoList;
    }

    @Override
    public SysPermission getSysPermission(Long perId) {
        if (perId == null) {
            return null;
        }
        SysPermission permission = sysPermissionMapper.selectById(perId);
        return permission;
    }

    @Transactional
    @Override
    public SysPermission save(SysPermission sysPermission) {
        if (sysPermission == null) {
            return null;
        }
        Long perId = sysPermission.getPerId();
        sysPermission.setResType(1);
        if (perId == null) {
            //新增，生成 orderFlag
            if (sysPermission.getParentId() != null&&sysPermission.getParentId()!=-1) {
                //子节点
                SysPermission parentPermission = sysPermissionMapper.selectById(sysPermission.getParentId());
                if (parentPermission == null) {
                    throw new IllegalRequestParamException("非法的父节点信息，行为已经记录。");
                }

                //orderFlag 生成
                String orderFlag = parentPermission.getOrderFlag();
                if (parentPermission.isLeaf()) {
                    orderFlag += "001";
                    sysPermission.setOrderFlag(orderFlag);
                    sysPermissionMapper.updateLeafById(false, parentPermission.getPerId());
                } else {
                    //获取同级最后一个
                    SysPermission sysPermissionLast = getSysPermissionLast(sysPermission.getParentId());
                    String lastOrderFlag = sysPermissionLast.getOrderFlag();
                    String prefix = lastOrderFlag.substring(0, lastOrderFlag.length() - 3);
                    String end = lastOrderFlag.substring(lastOrderFlag.length() - 3);
                    if (Integer.parseInt(end) > 998) {
                        throw new RuntimeException("此节点子节点已超出数量限制，请选择其他父级节点");
                    }
                    end = StringUtil.fillNumZero(Long.parseLong(end) + 1, 3);
                    String newOrderFlag = prefix + end;
                    sysPermission.setOrderFlag(newOrderFlag);
                }
                if (parentPermission.getResType()==1){
                    sysPermission.setResType(2);
                }else if(parentPermission.getResType()==2){
                    sysPermission.setResType(3);
                }
            } else {
                //模块
                //获取同级最后一个
                SysPermission sysPermissionLast = getSysPermissionLast(-1L);
                String lastOrderFlag = sysPermissionLast.getOrderFlag();
                String prefix = lastOrderFlag.substring(0, lastOrderFlag.length() - 3);
                String end = lastOrderFlag.substring(lastOrderFlag.length() - 3);
                if (Integer.parseInt(end) > 998) {
                    throw new RuntimeException("此节点子节点已超出数量限制，请选择其他父级节点");
                }
                end = StringUtil.fillNumZero(Long.parseLong(end) + 1, 3);
                String newOrderFlag = prefix + end;
                sysPermission.setOrderFlag(newOrderFlag);
                sysPermission.setParentId(-1L);
            }
            sysPermission.setLeaf(true);
            sysPermissionMapper.insert(sysPermission);
            //为管理员添加权限
            sysRoleMapper.insertRolePermission(1L,sysPermission.getPerId());
            return sysPermission;
        }

        //修改
        sysPermission.setOrderFlag(null);
        sysPermission.setPerFlag(null);
        sysPermission.setLeaf(null);
        sysPermission.setCreator(null);
        sysPermission.setTargetType(null);
        sysPermission.setParentId(null);
        sysPermission.setResType(null);
        sysPermissionMapper.updateById(sysPermission);

        return sysPermission;
    }

    @Override
    public SysPermission getSysPermissionLast(Long parentId) {
        QueryWrapper query = new QueryWrapper();
        query.orderByDesc("orderFlag");
        query.eq("parentId", parentId);
        query.last("limit 1");

        return sysPermissionMapper.selectOne(query);
    }

    @Transactional
    @Override
    public void deleteById(Long perId) {
        sysPermissionMapper.deleteById(perId);
        sysPermissionMapper.deleteRolePermissionRelateByPerId(perId);
    }

    @Transactional
    @Override
    public void removeRolePermission(Long roleId, Long[] permissionIds) {
        for (Long permissionId : permissionIds) {

            //删除关系
            sysPermissionMapper.deleteRolePermissionRelate(roleId,permissionId);
        }
    }


}
